import time

from sqlalchemy import Column, String, Integer, DateTime, Text
from database import dbconnect, session_maker, model_list, model_dict

_, md, DBase = dbconnect()


class Job(DBase):
    __tablename__ = 'job'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    type = Column(Integer)
    state = Column(Integer)
    params = Column(Text)
    comment = Column(String(255))
    creator = Column(String(50))
    auditor = Column(String(50))
    create_time = Column(DateTime)
    audit_time = Column(DateTime)
    deny_reason = Column(String(255))

    # 查询所有
    def find_all(self):
        with session_maker() as session:
            result = session.query(Job).order_by(Job.id.desc()).all()
            list = model_list(result)
            return list

    # 查询待审批的工单
    def find_all_undo(self):
        with session_maker() as session:
            result = session.query(Job).filter_by(state=1).order_by(Job.id.desc()).all()
            list = model_list(result)
            return list

    # 根据id查询
    def find_by_id(self, id):
        with session_maker() as session:
            row = session.query(Job).filter_by(id=id).first()
            dict = model_dict(row)
            return dict

    # 指定分页的limit和offset的参数值
    def find_limit(self, start, count):
        with session_maker() as session:
            result = session.query(Job).order_by(Job.id.desc()).limit(count).offset(start).all()
            list = model_list(result)
            return list

    # 统计总数
    def get_total_count(self):
        with session_maker() as session:
            count = session.query(Job).count()
            return count

    # 新增一条job记录, state: 1代表待审批，2代表已完成
    def insert(self, type, comment, params, state=1):
        from flask import session as web_session
        with session_maker() as session:
            now = time.strftime('%Y-%m-%d %H:%M:%S')
            id = time.strftime('%Y%m%d%H%M%S')
            if state==1:
                new_row = Job(id=id, type=type, state=state, params=params, comment=comment,
                              creator=web_session.get('username'),
                              create_time=now)
            elif state==2:
                new_row = Job(id=id, type=type, state=state, params=params, comment=comment,
                              creator=web_session.get('username'),
                              create_time=now, audit_time=now)
            session.add(new_row)
        return id

    # 更新审批人，审批时间
    def approve_update(self, job_id, auditor, state, deny_reason):
        with session_maker() as session:
            now = time.strftime('%Y-%m-%d %H:%M:%S')
            session.query(Job).filter(Job.id == job_id).update({"auditor": auditor, "audit_time": now, "state": state, "deny_reason": deny_reason})
            return True


